package com.ssm.juc.thread;


/**
 * 线程状态打印
 */
public class ThreadStateTest {

    public static void main(String[] args) throws InterruptedException {
        // 创建State对象
        ThreadState state = new ThreadState();

        // 利用State对象创建Thread对象
        Thread thread = new Thread(state);
        // 输出线程状态
        System.out.println("新建线程：" + thread.getState());
        // 调用thread对象的start()方法，启动新线程
        thread.start();
        // 输出线程状态
        System.out.println("启动线程：" + thread.getState());
        // 当前线程休眠0.1秒，使新线程运行waitForASecond()方法
        Thread.sleep(100);
        // 输出线程状态
        System.out.println("计时等待：" + thread.getState());
        // 当前线程休眠1秒，使新线程运行waitForYears()方法
        Thread.sleep(1000);
        // 输出线程状态
        System.out.println("等待线程：" + thread.getState());
        // 调用state的notifyNow()方法
        state.notifyNow();
        // 输出线程状态
        System.out.println("唤醒线程：" + thread.getState());

        Thread bThread = createBThread(state);
        bThread.start();
        Thread.sleep(200);
        System.out.println("线程状态：" + thread.getState());

        // 当前线程休眠1秒，使新线程结束
        Thread.sleep(2000);
        // 输出线程状态
        System.out.println("终止线程：" + thread.getState());
    }

    private static Thread createBThread(Object lockObj) {
        return new Thread(() -> {

            synchronized (lockObj) {
                long startTime = System.currentTimeMillis();
                // 调试信息：请忽略
                //long lastNum = startTime;
                for (; ; ) {

                    long nowTime = System.currentTimeMillis();
                    // 调试信息：请忽略
                    //if (nowTime != lastNum && nowTime % 100 == 0) {
                    //    lastNum = nowTime;
                    //    System.out.println("obtain lock is bthread");
                   // }

                    if (nowTime - startTime > 1000) {
                        break;
                    }
                }
            }
        });
    }

}